<template>
  <div class="code-gen-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>代码生成</span>
          <el-button type="primary" @click="handleGenCode">
            <el-icon><Download /></el-icon>
            生成代码
          </el-button>
        </div>
      </template>
      
      <el-form :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="数据源">
          <el-select v-model="queryParams.dataName" placeholder="请选择数据源" clearable>
            <el-option v-for="item in dataNameList" :key="item" :value="item" :label="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="表名称">
          <el-input v-model="queryParams.tableName" placeholder="请输入表名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table 
        :data="tableList" 
        :loading="loading"
        @selection-change="handleSelectionChange"
        row-key="tableId"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="dataName" label="数据源" />
        <el-table-column prop="tableName" label="表名称" />
        <el-table-column prop="tableComment" label="表描述" />
        <el-table-column prop="className" label="实体类名" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="handlePreview(row)">预览</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="getList"
        @current-change="getList"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Download, Search, Refresh } from '@element-plus/icons-vue';
import { listTable, getDataNames, delTable, genCode, previewTable } from '@/api/gen';
import type { GenTableQuery, GenTableVo } from '@/api/model/genModel';

defineOptions({
  name: 'CodeGen',
});

const tableList = ref<GenTableVo[]>([]);
const loading = ref(false);
const total = ref(0);
const dataNameList = ref<string[]>([]);
const selectedRows = ref<GenTableVo[]>([]);

const queryParams = ref<GenTableQuery>({
  pageNum: 1,
  pageSize: 10,
  tableName: '',
  tableComment: '',
  dataName: '',
});

// 获取数据源列表
async function getDataNameList() {
  try {
    const res = await getDataNames();
    dataNameList.value = res.data || [];
  } catch (error) {
    console.error('获取数据源列表失败:', error);
  }
}

// 获取表格列表
async function getList() {
  loading.value = true;
  try {
    const response = await listTable(queryParams.value);
    tableList.value = response.rows || [];
    total.value = response.total || 0;
  } catch (error) {
    console.error('获取表格列表失败:', error);
    ElMessage.error('获取表格列表失败');
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    tableName: '',
    tableComment: '',
    dataName: '',
  };
  getList();
}

// 选择变化
function handleSelectionChange(selection: GenTableVo[]) {
  selectedRows.value = selection;
}

// 预览
function handlePreview(row: GenTableVo) {
  ElMessage.info('预览功能待实现');
}

// 编辑
function handleEdit(row: GenTableVo) {
  ElMessage.info('编辑功能待实现');
}

// 删除
async function handleDelete(row: GenTableVo) {
  try {
    await ElMessageBox.confirm(`确认删除表 "${row.tableName}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    await delTable(row.tableId);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

// 生成代码
async function handleGenCode() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要生成代码的表');
    return;
  }
  
  try {
    const tableIds = selectedRows.value.map(row => row.tableId);
    await genCode(tableIds.join(','));
    ElMessage.success('代码生成成功');
  } catch (error) {
    console.error('代码生成失败:', error);
    ElMessage.error('代码生成失败');
  }
}

onMounted(() => {
  getList();
  getDataNameList();
});
</script>

<style scoped>
.code-gen-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-right: 20px;
}
</style>